public class Solution583 {
    public int minDistance(String word1, String word2) {
        int n = word2.length();
        int m = word1.length();
        int[][] dp = new int[n][m];
        for (int i = 0; i < n; i++) {
            char c2 = word2.charAt(i);
            for (int j = 0; j < m; j++) {
                char c1 = word1.charAt(j);
                if(c1 == c2){
                    int lastNum = (i == 0) || (j == 0) ? 0: dp[i-1][j-1];
                    dp[i][j] = lastNum + 1;
                }
                else{
                    int lastRow = i == 0 ? 0 : dp[i-1][j];
                    int lastCol = j == 0 ? 0 : dp[i][j-1];
                    dp[i][j] = Math.max(lastCol, lastRow);
                }
            }
        }
        return n + m - 2 * dp[n-1][m-1];
    }

    public static void main(String[] args) {
        Solution583 s = new Solution583();
        System.out.println(s.minDistance("leetcode",
                "etco"));
    }
}
